import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const products = [
    { id: 1, name: '手机', price: 1000, quantity: 1 },
    { id: 2, name: '电脑', price: 2000, quantity: 1 },
    { id: 3, name: '键盘', price: 200, quantity: 2 }
];

export default new Vuex.Store({
    state: {
        cart: products
    },
    mutations: {
        ADD_PRODUCT(state, product) {
            const existingProduct = state.cart.find(p => p.id === product.id);
            if (existingProduct) {
                existingProduct.quantity++;
            } else {
                state.cart.push({ ...product, quantity: 1 });
            }
        },
        REMOVE_PRODUCT(state, productId) {
            state.cart = state.cart.filter(product => product.id!== productId);
        },
        UPDATE_PRODUCT_QUANTITY(state, { productId, quantity }) {
            const product = state.cart.find(p => p.id === productId);
            if (product) {
                product.quantity = quantity;
            }
        }
    },
    actions: {
        addProduct({ commit }, product) {
            commit('ADD_PRODUCT', product);
        },
        removeProduct({ commit }, productId) {
            commit('REMOVE_PRODUCT', productId);
        },
        updateProductQuantity({ commit }, { productId, quantity }) {
            commit('UPDATE_PRODUCT_QUANTITY', { productId, quantity });
        }
    },
    getters: {
        totalPrice(state) {
            return state.cart.reduce((total, product) => total + product.price * product.quantity, 0);
        }
    }
});    